package com.example.show_auto.ui.pages

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.show_auto.ui.utils.OppoCompatibilityFix
import com.example.show_auto.viewmodel.MainViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.runtime.collectAsState
import com.example.show_auto.data.Chef
import com.example.show_auto.data.Skill



/**
 * 厨师分类查询结果页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChefCategoryQueryPage(
    onMenuClick: () -> Unit,
    onBackClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    // 获取 ViewModel 和游戏数据
    val viewModel: MainViewModel = viewModel()
    val gameData by viewModel.gameData.collectAsState()
    val uiState by viewModel.uiState.collectAsState()
    
    // 查询类型筛选状态
    var selectedQueryType by remember { mutableStateOf<String>("全部") }
    var isQueryTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 加成类型筛选状态（仅在基修厨师时显示）
    var selectedBonusType by remember { mutableStateOf<String>("全部") }
    var isBonusTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 筛选类型状态（仅在加成类型为技法加成时显示）
    var selectedFilterType by remember { mutableStateOf<String>("全部") }
    var isFilterTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 光环类型筛选状态（仅在光环厨师时显示）
    var selectedAuraType by remember { mutableStateOf<String>("全部") }
    var isAuraTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 光环筛选类型状态（仅在光环类型为技法光环时显示）
    var selectedAuraFilterType by remember { mutableStateOf<String>("全部") }
    var isAuraFilterTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 采集类型筛选状态（仅在采集厨师时显示）
    var selectedCollectionTypes by remember { mutableStateOf(setOf<String>()) }
    

    var isCollectionTypeDropdownExpanded by remember { mutableStateOf(false) }
    
    // 是否显示所有厨师的状态（默认只显示已拥有的）
    var showAllChefs by remember { mutableStateOf(false) }
    
    // 列表状态，用于控制滚动
    val listState = rememberLazyListState()
    
    // 监听selectedQueryType变化，滚动到顶部，并重置加成类型和筛选类型
    LaunchedEffect(selectedQueryType) {
        listState.animateScrollToItem(0)
        // 当查询类型改变时，重置加成类型和筛选类型为"全部"
        selectedBonusType = "全部"
        selectedFilterType = "全部"
        // 重置光环类型和光环筛选类型为"全部"
        selectedAuraType = "全部"
        selectedAuraFilterType = "全部"
        // 重置采集类型为空集合
        selectedCollectionTypes = emptySet()
        // 重置显示所有厨师状态
        showAllChefs = false
    }
    
    // 监听selectedBonusType变化，重置筛选类型
    LaunchedEffect(selectedBonusType) {
        // 当加成类型改变时，重置筛选类型为"全部"
        selectedFilterType = "全部"
    }
    
    // 监听selectedAuraType变化，重置光环筛选类型
    LaunchedEffect(selectedAuraType) {
        // 当光环类型改变时，重置光环筛选类型为"全部"
        selectedAuraFilterType = "全部"
    }
    
    // 获取所有厨师数据
    val allChefs = gameData?.chefs ?: emptyList()
    val skills = gameData?.skills ?: emptyList()
    
    // 监听showAllChefs变化，同步更新selectedFilterType的值
    LaunchedEffect(showAllChefs) {
        // 当显示状态改变时，如果当前选择了特定的筛选类型，需要同步更新其值
        if (selectedFilterType != "全部") {
            // 获取当前筛选类型的基础名称（去掉加成值部分）
            val baseFilterType = when {
                selectedFilterType.startsWith("炒") -> "炒"
                selectedFilterType.startsWith("煮") -> "煮"
                selectedFilterType.startsWith("切") -> "切"
                selectedFilterType.startsWith("炸") -> "炸"
                selectedFilterType.startsWith("烤") -> "烤"
                selectedFilterType.startsWith("蒸") -> "蒸"
                selectedFilterType.startsWith("男") -> "男"
                selectedFilterType.startsWith("女") -> "女"
                selectedFilterType.startsWith("全体") -> "全体"
                selectedFilterType.startsWith("1星") -> "1星"
                selectedFilterType.startsWith("2星") -> "2星"
                selectedFilterType.startsWith("3星") -> "3星"
                selectedFilterType.startsWith("4星") -> "4星"
                selectedFilterType.startsWith("5星") -> "5星"
                else -> selectedFilterType
            }
            
            // 根据当前状态重新计算加成值并更新selectedFilterType
            val chefsToCalculate = getChefsForBonusCalculation(
                allChefs, 
                skills, 
                showAllChefs, 
                selectedQueryType, 
                selectedBonusType
            )
            
            val newTotal = when (baseFilterType) {
                "炒" -> calculateTotalBonus(chefsToCalculate, skills, "炒技法+", showAllChefs)
                "煮" -> calculateTotalBonus(chefsToCalculate, skills, "煮技法+", showAllChefs)
                "切" -> calculateTotalBonus(chefsToCalculate, skills, "切技法+", showAllChefs)
                "炸" -> calculateTotalBonus(chefsToCalculate, skills, "炸技法+", showAllChefs)
                "烤" -> calculateTotalBonus(chefsToCalculate, skills, "烤技法+", showAllChefs)
                "蒸" -> calculateTotalBonus(chefsToCalculate, skills, "蒸技法+", showAllChefs)
                "男" -> calculateTotalBonus(chefsToCalculate, skills, "全体男厨师", showAllChefs)
                "女" -> calculateTotalBonus(chefsToCalculate, skills, "全体女厨师", showAllChefs)
                "全体" -> calculateTotalBonus(chefsToCalculate, skills, "全体厨师全技法", showAllChefs)
                "1星" -> when (selectedBonusType) {
                    "售价加成" -> calculateTotalBonus(chefsToCalculate, skills, "1星菜谱售价+", showAllChefs)
                    "菜谱数量加成" -> calculateTotalBonus(chefsToCalculate, skills, "1星菜谱上限+", showAllChefs)
                    else -> 0
                }
                "2星" -> when (selectedBonusType) {
                    "售价加成" -> calculateTotalBonus(chefsToCalculate, skills, "2星菜谱售价+", showAllChefs)
                    "菜谱数量加成" -> calculateTotalBonus(chefsToCalculate, skills, "2星菜谱上限+", showAllChefs)
                    else -> 0
                }
                "3星" -> when (selectedBonusType) {
                    "售价加成" -> calculateTotalBonus(chefsToCalculate, skills, "3星菜谱售价+", showAllChefs)
                    "菜谱数量加成" -> calculateTotalBonus(chefsToCalculate, skills, "3星菜谱上限+", showAllChefs)
                    else -> 0
                }
                "4星" -> when (selectedBonusType) {
                    "售价加成" -> calculateTotalBonus(chefsToCalculate, skills, "4星菜谱售价+", showAllChefs)
                    "菜谱数量加成" -> calculateTotalBonus(chefsToCalculate, skills, "4星菜谱上限+", showAllChefs)
                    else -> 0
                }
                "5星" -> when (selectedBonusType) {
                    "售价加成" -> calculateTotalBonus(chefsToCalculate, skills, "5星菜谱售价+", showAllChefs)
                    "菜谱数量加成" -> calculateTotalBonus(chefsToCalculate, skills, "5星菜谱上限+", showAllChefs)
                    else -> 0
                }
                else -> 0
            }
            
            // 更新selectedFilterType为新的加成值
            val suffix = when (selectedBonusType) {
                "售价加成" -> "%"
                "菜谱数量加成" -> ""
                else -> ""
            }
            selectedFilterType = "$baseFilterType（+$newTotal$suffix）"
        }
    }
    
    // 获取所有可用的查询类型选项
    val queryTypeOptions = remember {
        listOf("全部", "贵客厨师", "基修厨师", "光环厨师", "采集厨师")
    }
    
    // 获取加成类型选项
    val bonusTypeOptions = remember {
        listOf("全部", "技法加成", "售价加成", "菜谱数量加成")
    }
    
    // 获取筛选类型选项（包含总加成值）
    val filterTypeOptions = remember(allChefs, skills, showAllChefs, selectedQueryType, selectedBonusType) {
        val options = mutableListOf<String>()
        
        // 添加"全部"选项
        options.add("全部")
        
        // 获取满足当前筛选条件的厨师列表
        val chefsToCalculate = getChefsForBonusCalculation(
            allChefs, 
            skills, 
            showAllChefs, 
            selectedQueryType, 
            selectedBonusType
        )
        
        if (selectedBonusType == "技法加成") {
            // 技法加成的筛选类型选项
            val stirfryTotal = calculateTotalBonus(chefsToCalculate, skills, "炒技法+", showAllChefs)
            val boilTotal = calculateTotalBonus(chefsToCalculate, skills, "煮技法+", showAllChefs)
            val knifeTotal = calculateTotalBonus(chefsToCalculate, skills, "切技法+", showAllChefs)
            val fryTotal = calculateTotalBonus(chefsToCalculate, skills, "炸技法+", showAllChefs)
            val bakeTotal = calculateTotalBonus(chefsToCalculate, skills, "烤技法+", showAllChefs)
            val steamTotal = calculateTotalBonus(chefsToCalculate, skills, "蒸技法+", showAllChefs)
            val maleTotal = calculateTotalBonus(chefsToCalculate, skills, "全体男厨师", showAllChefs)
            val femaleTotal = calculateTotalBonus(chefsToCalculate, skills, "全体女厨师", showAllChefs)
            val allTotal = calculateTotalBonus(chefsToCalculate, skills, "全体厨师全技法", showAllChefs)
            
            // 添加带总加成的选项
            if (stirfryTotal > 0) options.add("炒（+$stirfryTotal）")
            if (boilTotal > 0) options.add("煮（+$boilTotal）")
            if (knifeTotal > 0) options.add("切（+$knifeTotal）")
            if (fryTotal > 0) options.add("炸（+$fryTotal）")
            if (bakeTotal > 0) options.add("烤（+$bakeTotal）")
            if (steamTotal > 0) options.add("蒸（+$steamTotal）")
            if (maleTotal > 0) options.add("男（+$maleTotal）")
            if (femaleTotal > 0) options.add("女（+$femaleTotal）")
            if (allTotal > 0) options.add("全体（+$allTotal）")
        } else if (selectedBonusType == "售价加成") {
            // 售价加成的筛选类型选项
            for (star in 1..5) {
                val total = calculateTotalBonus(chefsToCalculate, skills, "${star}星菜谱售价+", showAllChefs)
                if (total > 0) options.add("${star}星（+$total%）")
            }
        } else if (selectedBonusType == "菜谱数量加成") {
            // 菜谱数量加成的筛选类型选项
            for (star in 1..5) {
                val total = calculateTotalBonus(chefsToCalculate, skills, "${star}星菜谱上限+", showAllChefs)
                if (total > 0) options.add("${star}星（+$total）")
            }
        }
        
        options
    }
    
    // 获取光环类型选项
    val auraTypeOptions = remember {
        listOf("全部", "技法光环", "售价光环")
    }
    
    // 获取光环筛选类型选项
    val auraFilterTypeOptions = remember {
        listOf("全部", "炒", "煮", "切", "炸", "烤", "蒸", "其他")
    }
    
    // 获取采集类型选项
    val collectionTypeOptions = remember {
        listOf("肉", "菜", "鱼", "面")
    }
    
    // 根据选择的查询类型、加成类型和筛选类型过滤数据
    val filteredChefData = remember(allChefs, selectedQueryType, selectedBonusType, selectedFilterType, selectedAuraType, selectedAuraFilterType, selectedCollectionTypes, showAllChefs, skills) {
        // 根据showAllChefs状态决定显示范围
        val baseChefs = if (showAllChefs) {
            // 显示所有厨师（包括未拥有的）
            allChefs
        } else {
            // 只显示已拥有的厨师
            allChefs.filter { it.got }
        }
        
        // 临时调试信息
        println("DEBUG: selectedQueryType = $selectedQueryType")
        println("DEBUG: selectedBonusType = $selectedBonusType")
        println("DEBUG: selectedCollectionTypes = $selectedCollectionTypes")
        println("DEBUG: baseChefs.size = ${baseChefs.size}")
        println("DEBUG: allChefs.size = ${allChefs.size}")
        
        val filtered = if (selectedQueryType == "全部") {
            baseChefs
        } else {
            baseChefs.filter { chef ->
                val matchesQueryType = when (selectedQueryType) {
                    "贵客厨师" -> isGuestChef(chef, skills)
                    "基修厨师" -> isBasicCultivationChef(chef, skills)
                    "光环厨师" -> isAuraChef(chef, skills)
                    "采集厨师" -> isCollectionChef(chef, skills)
                    else -> true
                }
                
                // 如果是基修厨师且选择了特定加成类型，进行二次筛选
                if (selectedQueryType == "基修厨师" && selectedBonusType != "全部" && matchesQueryType) {
                    val matchesBonusType = matchesBonusType(chef, skills, selectedBonusType)
                    
                    // 如果加成类型是技法加成、售价加成或菜谱数量加成且选择了特定筛选类型，进行三次筛选
                    if ((selectedBonusType == "技法加成" || selectedBonusType == "售价加成" || selectedBonusType == "菜谱数量加成") && selectedFilterType != "全部" && matchesBonusType) {
                        matchesFilterType(chef, skills, selectedFilterType, selectedBonusType)
                    } else {
                        matchesBonusType
                    }
                } else if (selectedQueryType == "基修厨师" && selectedBonusType == "全部" && matchesQueryType) {
                    // 当加成类型为"全部"时，检查是否包含任何类型的加成技能
                    matchesBonusType(chef, skills, "全部")
                } else if (selectedQueryType == "光环厨师" && selectedAuraType != "全部" && matchesQueryType) {
                    // 如果是光环厨师且选择了特定光环类型，进行二次筛选
                    val matchesAuraType = matchesAuraType(chef, skills, selectedAuraType)
                    
                    // 调试信息
                    if (selectedAuraType == "售价光环") {
                        println("DEBUG: 厨师 ${chef.name} 光环厨师筛选结果: $matchesAuraType")
                    }
                    
                    // 如果光环类型是技法光环且选择了特定筛选类型，进行三次筛选
                    if (selectedAuraType == "技法光环" && selectedAuraFilterType != "全部" && matchesAuraType) {
                        val matchesFilter = matchesAuraFilterType(chef, skills, selectedAuraFilterType)
                        println("DEBUG: 厨师 ${chef.name} 技法筛选结果: $matchesFilter")
                        matchesFilter
                    } else if (selectedAuraType == "售价光环" && selectedAuraFilterType != "全部" && matchesAuraType) {
                        // 如果光环类型是售价光环且选择了特定筛选类型，进行三次筛选
                        val matchesFilter = matchesAuraFilterTypeForPrice(chef, skills, selectedAuraFilterType)
                        println("DEBUG: 厨师 ${chef.name} 售价技法筛选结果: $matchesFilter")
                        matchesFilter
                    } else {
                        matchesAuraType
                    }
                } else if (selectedQueryType == "光环厨师" && selectedAuraType == "全部" && matchesQueryType) {
                    // 如果是光环厨师且光环类型为"全部"，需要区分技法光环和售价光环
                    // 技法光环：按照新的实验室逻辑判断
                    val isTechniqueAura = isTechniqueAuraChef(chef, skills)
                    // 售价光环：其他光环厨师
                    val isPriceAura = isPriceAuraChef(chef, skills)
                    
                    // 只要满足任一条件即可
                    isTechniqueAura || isPriceAura
                } else if (selectedQueryType == "采集厨师" && selectedAuraType != "全部" && matchesQueryType) {
                    // 如果是采集厨师且选择了特定光环类型，进行二次筛选
                    val matchesAuraType = matchesAuraType(chef, skills, selectedAuraType)
                    
                    // 调试信息
                    if (selectedAuraType == "技法光环") {
                        println("DEBUG: 厨师 ${chef.name} 采集厨师筛选结果: $matchesAuraType")
                    }
                    
                    // 如果光环类型是技法光环且选择了特定筛选类型，进行三次筛选
                    if (selectedAuraType == "技法光环" && selectedAuraFilterType != "全部" && matchesAuraType) {
                        val matchesFilter = matchesAuraFilterType(chef, skills, selectedAuraFilterType)
                        println("DEBUG: 厨师 ${chef.name} 采集技法筛选结果: $matchesFilter")
                        matchesFilter
                    } else if (selectedAuraType == "售价光环" && selectedAuraFilterType != "全部" && matchesAuraType) {
                        // 如果光环类型是售价光环且选择了特定筛选类型，进行三次筛选
                        val matchesFilter = matchesAuraFilterTypeForPrice(chef, skills, selectedAuraFilterType)
                        println("DEBUG: 厨师 ${chef.name} 采集售价技法筛选结果: $matchesFilter")
                        matchesFilter
                    } else {
                        // 光环类型筛选通过后，进行采集类型筛选
                        if (selectedCollectionTypes.isNotEmpty()) {
                            matchesCollectionTypes(chef, selectedCollectionTypes)
                        } else {
                            matchesAuraType
                        }
                    }
                } else if (selectedQueryType == "采集厨师" && selectedAuraType == "全部" && matchesQueryType) {
                    // 如果是采集厨师且光环类型为"全部"，进行采集类型筛选
                    if (selectedCollectionTypes.isNotEmpty()) {
                        matchesCollectionTypes(chef, selectedCollectionTypes)
                    } else {
                        true
                    }
                } else if (selectedQueryType == "采集厨师" && matchesQueryType) {
                    // 如果是采集厨师，进行采集类型筛选
                    if (selectedCollectionTypes.isNotEmpty()) {
                        matchesCollectionTypes(chef, selectedCollectionTypes)
                    } else {
                        true
                    }
                } else {
                    matchesQueryType
                }
            }
        }
        
        println("DEBUG: filtered.size = ${filtered.size}")
        
        // 排序：根据查询类型使用不同的排序规则
        if (selectedQueryType == "贵客厨师") {
            // 贵客厨师排序：只根据厨师星级排序
            filtered.sortedWith { chef1, chef2 ->
                // 按星级降序排序（高星级优先）
                val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
                if (rarityComparison != 0) {
                    rarityComparison
                } else {
                    // 星级相同时，按厨师名称排序（保证排序稳定性）
                                chef1.name.compareTo(chef2.name)
                }
            }
        } else if (selectedQueryType == "光环厨师") {
            // 光环厨师排序：优先按拥有状态降序（已拥有的优先），然后按修炼状态降序，修炼状态相同时按星级降序，最后按名称
            filtered.sortedWith { chef1, chef2 ->
                // 1. 首先按拥有状态降序排序（已拥有的优先，未拥有的永远在最后）
                val ownedComparison = chef2.got.compareTo(chef1.got)
                if (ownedComparison != 0) {
                    ownedComparison
                } else {
                    // 拥有状态相同时，按修炼状态降序排序（已修炼的优先）
                    val ultimateComparison = chef2.ult.compareTo(chef1.ult)
                    if (ultimateComparison != 0) {
                        ultimateComparison
                    } else {
                        // 修炼状态相同时，按星级降序排序
                        val rarityComparison = chef2.rarity.compareTo(chef1.rarity)
                        if (rarityComparison != 0) {
                            rarityComparison
                        } else {
                            // 星级相同时，按厨师名称排序（保证排序稳定性）
                            chef1.name.compareTo(chef2.name)
                        }
                    }
                }
            }
        } else if (selectedQueryType == "采集厨师") {
            // 采集厨师排序：按照公式"素材加成 + 暴击率 × 暴击素材"计算排序值降序
            filtered.sortedWith { chef1, chef2 ->
                val score1 = calculateCollectionScore(chef1, skills)
                val score2 = calculateCollectionScore(chef2, skills)
                
                // 首先按总分降序排序
                val scoreComparison = score2.totalScore.compareTo(score1.totalScore)
                if (scoreComparison != 0) {
                    scoreComparison
                } else {
                    // 总分相同时，按素材加成降序排序
                    val materialBonusComparison = score2.materialBonus.compareTo(score1.materialBonus)
                    if (materialBonusComparison != 0) {
                        materialBonusComparison
                    } else {
                        // 素材加成相同时，按暴击率×暴击素材降序排序
                        val critProductComparison = score2.critProduct.compareTo(score1.critProduct)
                        if (critProductComparison != 0) {
                            critProductComparison
                        } else {
                            // 都相同时，按厨师名称排序（保证排序稳定性）
                            chef1.name.compareTo(chef2.name)
                        }
                    }
                }
            }
        } else {
            // 其他查询类型：已修炼的厨师排在前面，未修炼的厨师排在后面
            filtered.sortedWith { chef1, chef2 ->
                when {
                    chef1.ult && !chef2.ult -> -1  // chef1已修炼，chef2未修炼，chef1排在前面
                    !chef1.ult && chef2.ult -> 1   // chef1未修炼，chef2已修炼，chef2排在后面
                    else -> 0  // 修炼状态相同，保持原有顺序
                }
            }
        }
    }

    OppoCompatibilityFix.FixedLayoutContainer(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部应用栏
        TopAppBar(
            title = { 
                Text(text = "厨师分类查询")
            },
            navigationIcon = {
                IconButton(onClick = onMenuClick) {
                    Icon(imageVector = Icons.Default.Menu, contentDescription = "菜单")
                }
            },
            actions = {
                IconButton(onClick = onBackClick) {
                    Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "返回")
                }
            },
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
            )
        )

        // 页面内容
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(OppoCompatibilityFix.getFixedSpacing(16.dp)),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // 筛选区域
            Column(
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 第一行：查询类型筛选
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.Bottom
                ) {
                    // 查询类型筛选下拉框
                    ExposedDropdownMenuBox(
                        expanded = isQueryTypeDropdownExpanded,
                        onExpandedChange = { isQueryTypeDropdownExpanded = it },
                        modifier = Modifier.weight(1f)
                    ) {
                        OutlinedTextField(
                            value = selectedQueryType,
                            onValueChange = {},
                            readOnly = true,
                            label = { Text("选择查询类型", fontSize = 12.sp) },
                            textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                            trailingIcon = {
                                ExposedDropdownMenuDefaults.TrailingIcon(expanded = isQueryTypeDropdownExpanded)
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .menuAnchor()
                        )
                        
                        ExposedDropdownMenu(
                            expanded = isQueryTypeDropdownExpanded,
                            onDismissRequest = { isQueryTypeDropdownExpanded = false }
                        ) {
                            queryTypeOptions.forEach { option ->
                                DropdownMenuItem(
                                    text = { Text(option, fontSize = 12.sp) },
                                    onClick = {
                                        selectedQueryType = option
                                        isQueryTypeDropdownExpanded = false
                                    },
                                    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                    modifier = Modifier.height(32.dp)
                                )
                            }
                        }
                    }
                    
                    // 查看全部/只看已拥有按钮
                    Button(
                        onClick = { 
                            // 切换显示所有厨师的状态
                            showAllChefs = !showAllChefs
                        },
                        modifier = Modifier
                            .width(90.dp)
                            .height(65.dp)
                            .padding(top = 8.dp),
                        shape = RoundedCornerShape(4.dp),
                        contentPadding = PaddingValues(0.dp),
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (showAllChefs) 
                                MaterialTheme.colorScheme.secondary 
                            else 
                                MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Text(
                            text = if (showAllChefs) "只看已拥有" else "查看全部",
                            fontSize = 11.sp,
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                    }
                }
                
                // 第二行：加成类型筛选（仅在基修厨师时显示）
                if (selectedQueryType == "基修厨师") {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 加成类型下拉框
                        ExposedDropdownMenuBox(
                            expanded = isBonusTypeDropdownExpanded,
                            onExpandedChange = { isBonusTypeDropdownExpanded = it },
                            modifier = Modifier.weight(1f)
                        ) {
                            OutlinedTextField(
                                value = selectedBonusType,
                                onValueChange = {},
                                readOnly = true,
                                label = { Text("加成类型", fontSize = 12.sp) },
                                textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                                trailingIcon = {
                                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = isBonusTypeDropdownExpanded)
                                },
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .menuAnchor()
                            )
                            
                            ExposedDropdownMenu(
                                expanded = isBonusTypeDropdownExpanded,
                                onDismissRequest = { isBonusTypeDropdownExpanded = false }
                            ) {
                                bonusTypeOptions.forEach { option ->
                                    DropdownMenuItem(
                                        text = { Text(option, fontSize = 12.sp) },
                                        onClick = {
                                            selectedBonusType = option
                                            isBonusTypeDropdownExpanded = false
                                        },
                                        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                        modifier = Modifier.height(32.dp)
                                    )
                                }
                            }
                        }
                        
                        // 筛选类型下拉框（在技法加成、售价加成或菜谱数量加成时显示）
                        if (selectedBonusType == "技法加成" || selectedBonusType == "售价加成" || selectedBonusType == "菜谱数量加成") {
                            ExposedDropdownMenuBox(
                                expanded = isFilterTypeDropdownExpanded,
                                onExpandedChange = { isFilterTypeDropdownExpanded = it },
                                modifier = Modifier.weight(1f)
                            ) {
                                OutlinedTextField(
                                    value = selectedFilterType,
                                    onValueChange = {},
                                    readOnly = true,
                                    label = { Text("筛选类型", fontSize = 12.sp) },
                                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                                    trailingIcon = {
                                        ExposedDropdownMenuDefaults.TrailingIcon(expanded = isFilterTypeDropdownExpanded)
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .menuAnchor()
                                )
                                
                                ExposedDropdownMenu(
                                    expanded = isFilterTypeDropdownExpanded,
                                    onDismissRequest = { isFilterTypeDropdownExpanded = false }
                                ) {
                                    filterTypeOptions.forEach { option ->
                                        DropdownMenuItem(
                                            text = { Text(option, fontSize = 12.sp) },
                                            onClick = {
                                                selectedFilterType = option
                                                isFilterTypeDropdownExpanded = false
                                            },
                                            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                            modifier = Modifier.height(32.dp)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 第三行：光环类型筛选（仅在光环厨师时显示）
                if (selectedQueryType == "光环厨师") {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 光环类型下拉框
                        ExposedDropdownMenuBox(
                            expanded = isAuraTypeDropdownExpanded,
                            onExpandedChange = { isAuraTypeDropdownExpanded = it },
                            modifier = Modifier.weight(1f)
                        ) {
                            OutlinedTextField(
                                value = selectedAuraType,
                                onValueChange = {},
                                readOnly = true,
                                label = { Text("光环类型", fontSize = 12.sp) },
                                textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                                trailingIcon = {
                                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = isAuraTypeDropdownExpanded)
                                },
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .menuAnchor()
                            )
                            
                            ExposedDropdownMenu(
                                expanded = isAuraTypeDropdownExpanded,
                                onDismissRequest = { isAuraTypeDropdownExpanded = false }
                            ) {
                                                                    auraTypeOptions.forEach { option ->
                                        DropdownMenuItem(
                                            text = { Text(option, fontSize = 12.sp) },
                                            onClick = {
                                                selectedAuraType = option
                                                isAuraTypeDropdownExpanded = false
                                            },
                                            contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                            modifier = Modifier.height(32.dp)
                                        )
                                    }
                            }
                        }
                        
                        // 光环筛选类型下拉框（在技法光环或售价光环时显示）
                        if (selectedAuraType == "技法光环" || selectedAuraType == "售价光环") {
                            ExposedDropdownMenuBox(
                                expanded = isAuraFilterTypeDropdownExpanded,
                                onExpandedChange = { isAuraFilterTypeDropdownExpanded = it },
                                modifier = Modifier.weight(1f)
                            ) {
                                OutlinedTextField(
                                    value = selectedAuraFilterType,
                                    onValueChange = {},
                                    readOnly = true,
                                    label = { Text("筛选类型", fontSize = 12.sp) },
                                    textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                                    trailingIcon = {
                                        ExposedDropdownMenuDefaults.TrailingIcon(expanded = isAuraFilterTypeDropdownExpanded)
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .menuAnchor()
                                )
                                
                                ExposedDropdownMenu(
                                    expanded = isAuraFilterTypeDropdownExpanded,
                                    onDismissRequest = { isAuraFilterTypeDropdownExpanded = false }
                                ) {
                                                                            auraFilterTypeOptions.forEach { option ->
                                            DropdownMenuItem(
                                                text = { Text(option, fontSize = 12.sp) },
                                                onClick = {
                                                    selectedAuraFilterType = option
                                                    isAuraFilterTypeDropdownExpanded = false
                                                },
                                                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                                modifier = Modifier.height(32.dp)
                                            )
                                        }
                                }
                            }
                        }
                    }
                }
                
                // 第四行：采集类型筛选（仅在采集厨师时显示）
                if (selectedQueryType == "采集厨师") {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        // 采集类型多选下拉框
                        ExposedDropdownMenuBox(
                            expanded = isCollectionTypeDropdownExpanded,
                            onExpandedChange = { isCollectionTypeDropdownExpanded = it },
                            modifier = Modifier.weight(1f)
                        ) {
                            OutlinedTextField(
                                value = if (selectedCollectionTypes.isEmpty()) "全部" else selectedCollectionTypes.joinToString("、"),
                                onValueChange = {},
                                readOnly = true,
                                label = { Text("采集类型", fontSize = 12.sp) },
                                textStyle = androidx.compose.ui.text.TextStyle(fontSize = 12.sp),
                                trailingIcon = {
                                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = isCollectionTypeDropdownExpanded)
                                },
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .menuAnchor()
                            )
                            
                            ExposedDropdownMenu(
                                expanded = isCollectionTypeDropdownExpanded,
                                onDismissRequest = { isCollectionTypeDropdownExpanded = false }
                            ) {
                                // 添加"全部"选项
                                DropdownMenuItem(
                                    text = { Text("全部", fontSize = 12.sp) },
                                    onClick = {
                                        selectedCollectionTypes = emptySet()
                                        isCollectionTypeDropdownExpanded = false
                                    },
                                    contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                    modifier = Modifier.height(32.dp)
                                )
                                
                                // 添加分隔线
                                HorizontalDivider()
                                
                                // 添加各个采集类型选项
                                collectionTypeOptions.forEach { option ->
                                    val isSelected = selectedCollectionTypes.contains(option)
                                    DropdownMenuItem(
                                        text = { 
                                            Text(
                                                text = option,
                                                fontSize = 12.sp,
                                                color = if (isSelected) 
                                                    MaterialTheme.colorScheme.onPrimary 
                                                else 
                                                    MaterialTheme.colorScheme.onSurface
                                            )
                                        },
                                        onClick = {
                                            // 点击时切换选中状态
                                            if (isSelected) {
                                                selectedCollectionTypes = selectedCollectionTypes - option
                                            } else {
                                                selectedCollectionTypes = selectedCollectionTypes + option
                                            }
                                        },
                                        contentPadding = PaddingValues(horizontal = 16.dp, vertical = 2.dp),
                                        modifier = Modifier
                                            .height(32.dp)
                                            .background(
                                                color = if (isSelected) 
                                                    MaterialTheme.colorScheme.primary 
                                                else 
                                                    Color.Transparent,
                                                shape = RoundedCornerShape(4.dp)
                                            )
                                    )
                                }
                            }
                        }
                    }
                }
            }

            // 结果列表
            LazyColumn(
                state = listState,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(filteredChefData) { chef ->
                    ChefCategoryItemCard(
                        chef = chef,
                        skills = skills,
                        isGuestChefQuery = selectedQueryType == "贵客厨师"
                    )
                }
            }
        }
    }
}

/**
 * 判断是否为贵客厨师
 * 新的逻辑：type = GuestDropCount 或者 GuestApearRate 或者 InvitationApearRate 的厨师
 * 同时检查普通技能和修炼技能
 */
private fun isGuestChef(chef: Chef, skills: List<Skill>): Boolean {
    // 检查普通技能
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null && baseSkill.effect != null) {
            val hasGuestEffectInBase = baseSkill.effect.any { effect ->
                effect.type in listOf("GuestDropCount", "GuestApearRate", "InvitationApearRate")
            }
            if (hasGuestEffectInBase) return true
        }
    }
    
    // 检查修炼技能
    if (chef.hasUltimateSkill()) {
        val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
            skills.find { it.skillId == skillId }
        }
        
        // 检查是否有符合条件的贵客相关技能
        val hasGuestEffectInUltimate = ultimateSkills.any { skill ->
            skill.effect?.any { effect ->
                // type必须是贵客相关类型
                effect.type in listOf("GuestDropCount", "GuestApearRate", "InvitationApearRate")
            } ?: false
        }
        if (hasGuestEffectInUltimate) return true
    }
    
    return false
}

/**
 * 检查技能描述是否为贵客相关技能
 * 与贵客率计算器页面的逻辑保持一致
 */
private fun isGuestRelatedSkill(desc: String): Boolean {
    // 稀有客人出现概率+*%
    if (desc.contains("稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 稀有客人赠礼数量*%概率提升*%
    if (desc.contains("稀有客人赠礼数量") && desc.contains("%概率提升") && desc.contains("%")) {
        return true
    }
    
    // 贵客赠礼数量*%概率提升*%
    if (desc.contains("贵客赠礼数量") && desc.contains("%概率提升") && desc.contains("%")) {
        return true
    }
    
    // 场上男性厨师稀有客人出现概率+*%
    if (desc.contains("场上男性厨师稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 场上女性厨师贵客率+*%
    if (desc.contains("场上女性厨师贵客率+") && desc.contains("%")) {
        return true
    }
    
    // 每制作一种神级料理稀有客人出现概率+*%
    if (desc.contains("每制作一种神级料理稀有客人出现概率+") && desc.contains("%")) {
        return true
    }
    
    // 场上厨师制作特级及以上料理时此料理贵客符文概率+*%
    if (desc.contains("场上厨师制作特级及以上料理时此料理贵客符文概率+") && desc.contains("%")) {
        return true
    }
    
    // 暴击相关技能类型
    // 每制作一种神级料理贵客赠礼翻倍概率+*%
    if (desc.contains("每制作一种神级料理贵客赠礼翻倍概率+") && desc.contains("%")) {
        return true
    }
    
    return false
}

/**
 * 获取贵客厨师的所有技能描述
 * 显示普通技能和修炼技能
 */
private fun getGuestRelatedSkillDescription(chef: Chef, skills: List<Skill>): String {
    val skillDescriptions = mutableListOf<String>()
    
    // 添加普通技能描述
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null) {
            skillDescriptions.add("${baseSkill.desc}")
        }
    }
    
    // 添加修炼技能描述
    if (chef.hasUltimateSkill()) {
        val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
            skills.find { it.skillId == skillId }
        }
        
        if (ultimateSkills.isNotEmpty()) {
            val ultimateSkillDescs = ultimateSkills.map { it.desc }
            skillDescriptions.add("${ultimateSkillDescs.joinToString("\n")}")
        }
    }
    
    return if (skillDescriptions.isNotEmpty()) {
        skillDescriptions.joinToString("\n")
    } else {
        "无技能"
    }
}

/**
 * 计算厨师的总贵客率加成
 * 用于贵客厨师排序
 */
private fun calculateTotalGuestRateBonus(chef: Chef, skills: List<Skill>): Double {
    var totalBonus = 0.0
    
    // 获取厨师的基础技能描述
    val baseSkillDesc = if (chef.skill > 0) {
        skills.find { it.skillId == chef.skill }?.desc ?: ""
    } else {
        ""
    }
    
    // 获取厨师的修炼技能描述
    val ultimateSkillDesc = getChefSkillDescription(chef, skills)
    
    // 合并厨师技能描述
    val combinedSkillDesc = "$baseSkillDesc $ultimateSkillDesc"
    
    // 计算厨师技能中的贵客率加成
    // 稀有客人出现概率+*%
    val guestRatePattern = "稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val guestRateMatches = guestRatePattern.findAll(combinedSkillDesc)
    for (match in guestRateMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 稀有客人赠礼数量*%概率提升*%
    val giftQuantityPattern = "稀有客人赠礼数量.*?(\\d+(?:\\.\\d+)?)%.*?概率提升.*?(\\d+(?:\\.\\d+)?)%".toRegex()
    val giftQuantityMatches = giftQuantityPattern.findAll(combinedSkillDesc)
    for (match in giftQuantityMatches) {
        val giftQuantity = match.groupValues[1].toDoubleOrNull() ?: 0.0
        val probabilityIncrease = match.groupValues[2].toDoubleOrNull() ?: 0.0
        // 取两个值中的较大值作为技能强度
        totalBonus += maxOf(giftQuantity, probabilityIncrease)
    }
    
    // 贵客赠礼数量*%概率提升*%
    val guestGiftPattern = "贵客赠礼数量.*?(\\d+(?:\\.\\d+)?)%.*?概率提升.*?(\\d+(?:\\.\\d+)?)%".toRegex()
    val guestGiftMatches = guestGiftPattern.findAll(combinedSkillDesc)
    for (match in guestGiftMatches) {
        val giftQuantity = match.groupValues[1].toDoubleOrNull() ?: 0.0
        val probabilityIncrease = match.groupValues[2].toDoubleOrNull() ?: 0.0
        // 取两个值中的较大值作为技能强度
        totalBonus += maxOf(giftQuantity, probabilityIncrease)
    }
    
    // 场上男性厨师稀有客人出现概率+*%
    val maleChefPattern = "场上男性厨师稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val maleChefMatches = maleChefPattern.findAll(combinedSkillDesc)
    for (match in maleChefMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 场上女性厨师贵客率+*%
    val femaleChefPattern = "场上女性厨师贵客率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val femaleChefMatches = femaleChefPattern.findAll(combinedSkillDesc)
    for (match in femaleChefMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 每制作一种神级料理稀有客人出现概率+*%
    val divineRecipePattern = "每制作一种神级料理稀有客人出现概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineRecipeMatches = divineRecipePattern.findAll(combinedSkillDesc)
    for (match in divineRecipeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 场上厨师制作特级及以上料理时此料理贵客符文概率+*%
    val runePattern = "场上厨师制作特级及以上料理时此料理贵客符文概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val runeMatches = runePattern.findAll(combinedSkillDesc)
    for (match in runeMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value
    }
    
    // 暴击相关技能类型
    // 每制作一种神级料理贵客赠礼翻倍概率+*% (值*3)
    val divineGiftPattern = "每制作一种神级料理贵客赠礼翻倍概率\\+(\\d+(?:\\.\\d+)?)%".toRegex()
    val divineGiftMatches = divineGiftPattern.findAll(combinedSkillDesc)
    for (match in divineGiftMatches) {
        val value = match.groupValues[1].toDoubleOrNull() ?: 0.0
        totalBonus += value * 3 // 按贵客率计算器页面的逻辑，这类技能值*3
    }
    
    return totalBonus
}

/**
 * 判断是否为基修厨师
 */
private fun isBasicCultivationChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    val skillDesc = getChefSkillDescription(chef, skills)
    // 基修厨师包括：全体技法加成、全体售价加成、全体菜谱数量加成等
    return skillDesc.contains("全体厨师") || skillDesc.contains("全体男厨师") || skillDesc.contains("全体女厨师") ||
           skillDesc.contains("售价") || skillDesc.contains("价格") || skillDesc.contains("收益") ||
           skillDesc.contains("菜谱上限")
}

/**
 * 判断是否为售价厨师
 */
private fun isPriceChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 使用effect字段判断，而不是技能描述
    return checkValidEffectForPriceAura(chef, skills)
}

/**
 * 判断是否为光环厨师
 * 全部光环厨师的查询逻辑：技能effect中，"condition": "Partial"，或者condition为Next，都是光环厨师
 * 技法光环厨师：按照查询采集编队页面的实验室中查询光环厨师逻辑
 * 售价光环厨师：其他光环厨师（不是技法光环的光环厨师）
 */
private fun isAuraChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 检查是否有符合条件的光环技能
    return ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            // 光环厨师条件：condition必须是"Partial"或"Next"
            effect.condition == "Partial" || effect.condition == "Next"
        } ?: false
    }
}

/**
 * 检查厨师的effect字段是否满足售价光环的条件
 */
private fun checkValidEffectForPriceAura(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    println("DEBUG: 检查厨师 ${chef.name} 的effect字段售价光环条件")
    
    val skillsList = chef.getAllUltimateSkills()
    println("DEBUG: 厨师 ${chef.name} 的修炼技能数量: ${skillsList.size}")
    
    for (ultimateSkillId in skillsList) {
        val skill = skills.find { it.skillId == ultimateSkillId }
        if (skill != null) {
            println("DEBUG: 厨师 ${chef.name} 技能ID: $ultimateSkillId, effect数量: ${skill.effect.size}")
            if (skill.effect.isNotEmpty()) {
                for (effect in skill.effect) {
                    println("DEBUG: 厨师 ${chef.name} effect: condition=${effect.condition}, type=${effect.type}, conditionType=${effect.conditionType}")
                    
                    // 检查condition是否为"Partial"且type为指定的类型
                    if (effect.condition == "Partial") {
                        val validTypes = listOf(
                            "UseStirfry", "UseKnife", "UseBake", "UseBoil", "UseSteam", "UseFry",
                            "BasicPriceUseStirfry", "BasicPriceUseKnife", "BasicPriceUseSteam", 
                            "BasicPriceUseBoil", "BasicPriceUseBake", "BasicPriceUseFry", 
                            "BasicPrice", "BasicPriceUseMeat"
                        )
                        if (effect.type in validTypes) {
                            println("DEBUG: 厨师 ${chef.name} 匹配Partial条件，type: ${effect.type}")
                            return true
                        }
                    }
                    
                    // 检查conditionType是否为"CookbookRarity"且condition为"Partial"
                    if (effect.conditionType == "CookbookRarity" && effect.condition == "Partial") {
                        println("DEBUG: 厨师 ${chef.name} 匹配CookbookRarity条件且condition为Partial")
                        return true
                    }
                }
            }
        }
    }
    
    println("DEBUG: 厨师 ${chef.name} 不匹配任何effect字段条件")
    return false
}

/**
 * 检查厨师是否匹配指定的光环筛选类型（技法类型）
 * 基于effect字段判断，与新的技法光环厨师逻辑保持一致
 */
private fun matchesAuraFilterType(chef: Chef, skills: List<Skill>, filterType: String): Boolean {
    if (filterType == "全部") return true
    if (!chef.hasUltimateSkill()) return false
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 技法类型映射
    val typeMapping = mapOf(
        "炒" to "Stirfry",
        "煮" to "Boil", 
        "切" to "Knife",
        "炸" to "Fry",
        "烤" to "Bake",
        "蒸" to "Steam"
    )
    
    val targetType = typeMapping[filterType] ?: return true
    
    // 检查是否有匹配的技法光环技能
    return ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            // 条件1：condition必须是"Partial"或"Next"
            val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
            
            // 条件2：type必须匹配指定技法类型
            val typeMatch = effect.type == targetType
            
            // 条件3：value必须大于0
            val valueMatch = (effect.value ?: 0) > 0
            
            conditionMatch && typeMatch && valueMatch
        } ?: false
    }
}

/**
 * 判断是否为采集厨师
 * 新的逻辑：type = Material_Gain 的厨师
 */
private fun isCollectionChef(chef: Chef, skills: List<Skill>): Boolean {
    // 检查普通技能
    if (chef.skill > 0) {
        val baseSkill = skills.find { it.skillId == chef.skill }
        if (baseSkill != null && baseSkill.effect != null) {
            val hasMaterialGainEffect = baseSkill.effect.any { effect ->
                effect.type == "Material_Gain"
            }
            if (hasMaterialGainEffect) return true
        }
    }
    
    // 检查修炼技能
    if (chef.hasUltimateSkill()) {
        val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
            skills.find { it.skillId == skillId }
        }
        
        // 检查是否有Material_Gain类型的effect
        val hasMaterialGainEffect = ultimateSkills.any { skill ->
            skill.effect?.any { effect ->
                effect.type == "Material_Gain"
            } ?: false
        }
        if (hasMaterialGainEffect) return true
    }
    
    return false
}

/**
 * 检查技能描述是否包含采集相关技能
 */
private fun hasCollectionSkill(skillDesc: String): Boolean {
    // 1. 暴击技能：技能描述包含"概率额外获得素材"相关文字
    val critPatterns = arrayOf(
        Regex("探索时有\\d+%概率额外获得\\d+%的?素材"),  // 忌璃格式：探索时有30%概率额外获得80%的素材
        Regex("有\\d+%概率额外获得\\d+%素材"),        // 四郎格式：有30%概率额外获得60%素材
        Regex("\\d+%概率额外获得\\d+%素材")           // 简化格式：30%概率额外获得60%素材
    )
    
    for (pattern in critPatterns) {
        if (pattern.containsMatchIn(skillDesc)) {
            return true
        }
    }
    
    // 2. 素材加成：技能描述包含"素材获得+X%"（不包括"全体*类素材获得+X%"）
    val materialGainPattern = Regex("素材获得\\+\\d+%")
    if (materialGainPattern.containsMatchIn(skillDesc)) {
        // 排除"全体*类素材获得+X%"的情况
        if (!skillDesc.contains("全体") || !skillDesc.contains("类素材获得")) {
            return true
        }
    }
    
    return false
}

/**
 * 获取厨师修炼技能描述
 * 对于采集厨师，只展示匹配到的采集相关技能
 */
private fun getChefSkillDescription(chef: Chef, skills: List<Skill>): String {
    if (!chef.hasUltimateSkill()) return "无修炼技能"
    
    // 如果是采集厨师，展示所有技能（因为现在基于effect.type判断，技能描述可能不直接相关）
    if (isCollectionChef(chef, skills)) {
        val allDescs = mutableListOf<String>()
        
        // 添加厨师自身技能
        if (chef.skill != 0) {
            val skill = skills.find { it.skillId == chef.skill }
            if (skill != null) {
                allDescs.add(skill.desc)
            }
        }
        
        // 添加厨师修炼技能
        chef.getAllUltimateSkills().forEach { sid ->
            val skill = skills.find { it.skillId == sid }
            if (skill != null) {
                allDescs.add(skill.desc)
            }
        }
        
        return if (allDescs.isEmpty()) "无技能" else allDescs.joinToString("\n")
    }
    
    // 非采集厨师，展示所有技能
    val descs = chef.getAllUltimateSkills().mapNotNull { sid ->
        skills.find { it.skillId == sid }?.desc
    }
    return if (descs.isEmpty()) "无修炼技能" else descs.joinToString("\n")
}

/**
 * 从技能描述中提取数值
 */
private fun extractNumberFromDesc(desc: String, keyword: String = ""): Int {
    if (keyword.isNotEmpty()) {
        // 从复合技能中提取特定关键词后的数值
        val pattern = when (keyword) {
            "售价" -> Regex("""售价\+(\d+)%""")
            "上限" -> Regex("""上限\+(\d+)""")
            "技法" -> Regex("""技法\+(\d+)""")
            else -> Regex("""\+(\d+)""")
        }
        val match = pattern.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 1
    } else {
        // 提取第一个+数字
        val regex = Regex("""\+(\d+)""")
        val match = regex.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 1
    }
}

/**
 * 判断技能是否为上场类技能（Partial）
 */
private fun isPartialSkill(skillId: Int): Boolean {
    return when (skillId) {
        // 场上所有厨师技法加成 - 上场类技能
        485, 486, 487, 488, 489, 490, 497, 498, 499 -> true
        // 其他技能默认为个人类技能
        else -> false
    }
}

/**
 * 检查厨师是否匹配指定的加成类型
 */
private fun matchesBonusType(chef: Chef, skills: List<Skill>, bonusType: String): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    val skillsList = chef.getAllUltimateSkills()
    
    for (ultimateSkillId in skillsList) {
        if (!isPartialSkill(ultimateSkillId)) {
            val skill = skills.find { it.skillId == ultimateSkillId }
            if (skill != null) {
                val desc = skill.desc
                
                when (bonusType) {
                    "全部" -> {
                        // 检查是否包含任何类型的加成技能
                        if (desc.contains("炒+") || desc.contains("煮+") || desc.contains("切+") ||
                            desc.contains("炸+") || desc.contains("烤+") || desc.contains("蒸+") ||
                            desc.contains("全技法+") || 
                            desc.contains("全体厨师") || desc.contains("全体男厨师") || desc.contains("全体女厨师") ||
                            desc.contains("1星菜谱售价+") || desc.contains("2星菜谱售价+") ||
                            desc.contains("3星菜谱售价+") || desc.contains("4星菜谱售价+") ||
                            desc.contains("5星菜谱售价+") ||
                            Regex("""\d+星和\d+星菜谱售价各\+\d+%""").containsMatchIn(desc) ||
                            Regex("""\d+火菜谱售价\+\d+%""").containsMatchIn(desc) ||
                            desc.contains("菜谱上限") ||
                            Regex("""\d+火菜谱上限\+\d+""").containsMatchIn(desc)) {
                            return true
                        }
                    }
                    "技法加成" -> {
                        // 检查是否包含技法加成
                        if (desc.contains("炒+") || desc.contains("煮+") || desc.contains("切+") ||
                            desc.contains("炸+") || desc.contains("烤+") || desc.contains("蒸+") ||
                            desc.contains("全技法+") || 
                            desc.contains("全体厨师") || desc.contains("全体男厨师") || desc.contains("全体女厨师")) {
                            return true
                        }
                    }
                    "售价加成" -> {
                        // 检查是否包含星级菜谱售价加成
                        println("DEBUG: 检查售价加成技能: $desc")
                        if (desc.contains("1星菜谱售价+") || desc.contains("2星菜谱售价+") ||
                            desc.contains("3星菜谱售价+") || desc.contains("4星菜谱售价+") ||
                            desc.contains("5星菜谱售价+") ||
                            Regex("""\d+星和\d+星菜谱售价各\+\d+%""").containsMatchIn(desc) ||
                            Regex("""\d+火菜谱售价\+\d+%""").containsMatchIn(desc)) {
                            println("DEBUG: 找到售价加成技能: $desc")
                            return true
                        }
                    }
                    "菜谱数量加成" -> {
                        // 检查是否包含菜谱数量上限加成
                        if (desc.contains("菜谱上限") || desc.contains("火菜谱上限") ||
                            desc.contains("上限+") ||
                            Regex("""\d+火菜谱上限\+\d+""").containsMatchIn(desc)) {
                            return true
                        }
                    }
                }
            }
        }
    }
    
    return false
}

/**
 * 检查厨师是否匹配指定的筛选类型
 */
private fun matchesFilterType(chef: Chef, skills: List<Skill>, filterType: String, bonusType: String = ""): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 从带总加成的选项文本中提取筛选类型
    val actualFilterType = when {
        filterType.startsWith("炒") -> "炒"
        filterType.startsWith("煮") -> "煮"
        filterType.startsWith("切") -> "切"
        filterType.startsWith("炸") -> "炸"
        filterType.startsWith("烤") -> "烤"
        filterType.startsWith("蒸") -> "蒸"
        filterType.startsWith("男") -> "男"
        filterType.startsWith("女") -> "女"
        filterType.startsWith("全体") -> "全体"
        filterType.startsWith("1星") -> "1星"
        filterType.startsWith("2星") -> "2星"
        filterType.startsWith("3星") -> "3星"
        filterType.startsWith("4星") -> "4星"
        filterType.startsWith("5星") -> "5星"
        else -> filterType
    }
    
    val skillsList = chef.getAllUltimateSkills()
    
    for (ultimateSkillId in skillsList) {
        if (!isPartialSkill(ultimateSkillId)) {
            val skill = skills.find { it.skillId == ultimateSkillId }
            if (skill != null) {
                val desc = skill.desc
                
                when (actualFilterType) {
                    "炒" -> {
                        // 只显示包含"炒技法+"技能的厨师
                        if (desc.contains("炒技法+")) {
                            return true
                        }
                    }
                    "煮" -> {
                        // 只显示包含"煮技法+"技能的厨师
                        if (desc.contains("煮技法+")) {
                            return true
                        }
                    }
                    "切" -> {
                        // 只显示包含"切技法+"技能的厨师
                        if (desc.contains("切技法+")) {
                            return true
                        }
                    }
                    "炸" -> {
                        // 只显示包含"炸技法+"技能的厨师
                        if (desc.contains("炸技法+")) {
                            return true
                        }
                    }
                    "烤" -> {
                        // 只显示包含"烤技法+"技能的厨师
                        if (desc.contains("烤技法+")) {
                            return true
                        }
                    }
                    "蒸" -> {
                        // 只显示包含"蒸技法+"技能的厨师
                        if (desc.contains("蒸技法+")) {
                            return true
                        }
                    }
                    "男" -> {
                        // 只显示包含"全体男厨师"技能的厨师
                        if (desc.contains("全体男厨师")) {
                            return true
                        }
                    }
                    "女" -> {
                        // 只显示包含"全体女厨师"技能的厨师
                        if (desc.contains("全体女厨师")) {
                            return true
                        }
                    }
                    "全体" -> {
                        // 只显示包含"全体厨师全技法"技能的厨师
                        if (desc.contains("全体厨师全技法")) {
                            return true
                        }
                    }

                    "1星" -> {
                        when (bonusType) {
                            "售价加成" -> {
                        // 只显示包含"1星菜谱售价+"技能的厨师
                        if (desc.contains("1星菜谱售价+")) {
                            return true
                                }
                            }
                            "菜谱数量加成" -> {
                                // 只显示包含"1星菜谱上限+"技能的厨师
                                if (desc.contains("1星菜谱上限+")) {
                                    return true
                                }
                            }
                        }
                    }
                    "2星" -> {
                        when (bonusType) {
                            "售价加成" -> {
                        if (desc.contains("2星菜谱售价+")) {
                            return true
                                }
                            }
                            "菜谱数量加成" -> {
                                if (desc.contains("2星菜谱上限+")) {
                                    return true
                                }
                            }
                        }
                    }
                    "3星" -> {
                        when (bonusType) {
                            "售价加成" -> {
                        if (desc.contains("3星菜谱售价+")) {
                            return true
                                }
                            }
                            "菜谱数量加成" -> {
                                if (desc.contains("3星菜谱上限+")) {
                                    return true
                                }
                            }
                        }
                    }
                    "4星" -> {
                        when (bonusType) {
                            "售价加成" -> {
                        if (desc.contains("4星菜谱售价+")) {
                            return true
                                }
                            }
                            "菜谱数量加成" -> {
                                if (desc.contains("4星菜谱上限+")) {
                                    return true
                                }
                            }
                        }
                    }
                    "5星" -> {
                        when (bonusType) {
                            "售价加成" -> {
                        if (desc.contains("5星菜谱售价+")) {
                            return true
                                }
                            }
                            "菜谱数量加成" -> {
                                if (desc.contains("5星菜谱上限+")) {
                                    return true
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    return false
}

/**
 * 计算技能描述中的总加成值
 */
private fun calculateTotalBonus(chefs: List<Chef>, skills: List<Skill>, skillKeyword: String, showAll: Boolean): Int {
    var totalBonus = 0
    
    chefs.forEach { chef ->
        // 根据showAll状态决定计算条件
        val shouldCalculate = if (showAll) {
            // 显示全部时，计算所有厨师的加成值（不管是否拥有或修炼）
            chef.hasUltimateSkill()
        } else {
            // 只显示已拥有时，只计算已拥有且已修炼的厨师
            chef.got && chef.ult && chef.hasUltimateSkill()
        }
        
        if (shouldCalculate) {
            val skillsList = chef.getAllUltimateSkills()
            
            for (ultimateSkillId in skillsList) {
                if (!isPartialSkill(ultimateSkillId)) {
                    val skill = skills.find { it.skillId == ultimateSkillId }
                    if (skill != null) {
                        val desc = skill.desc
                        
                        when (skillKeyword) {
                            "炒技法+" -> {
                                if (desc.contains("炒技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "煮技法+" -> {
                                if (desc.contains("煮技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "切技法+" -> {
                                if (desc.contains("切技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "炸技法+" -> {
                                if (desc.contains("炸技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "烤技法+" -> {
                                if (desc.contains("烤技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "蒸技法+" -> {
                                if (desc.contains("蒸技法+")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "全体男厨师" -> {
                                if (desc.contains("全体男厨师")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "全体女厨师" -> {
                                if (desc.contains("全体女厨师")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "全体厨师全技法" -> {
                                if (desc.contains("全体厨师全技法")) {
                                    totalBonus += extractNumberFromDesc(desc, "技法")
                                }
                            }
                            "1星菜谱售价+" -> {
                                if (desc.contains("1星菜谱售价+")) {
                                    totalBonus += extractNumberFromDesc(desc, "售价")
                                }
                                // 检查复合技能：*星和1星菜谱售价各+*%
                                val compositePattern = Regex("""(\d+)星和1星菜谱售价各\+(\d+)%""")
                                val match = compositePattern.find(desc)
                                if (match != null) {
                                    totalBonus += match.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查复合技能：1星和*星菜谱售价各+*%
                                val compositePattern2 = Regex("""1星和(\d+)星菜谱售价各\+(\d+)%""")
                                val match2 = compositePattern2.find(desc)
                                if (match2 != null) {
                                    totalBonus += match2.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查1火菜谱售价加成
                                val firePattern = Regex("""1火菜谱售价\+(\d+)%""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "2星菜谱售价+" -> {
                                if (desc.contains("2星菜谱售价+")) {
                                    totalBonus += extractNumberFromDesc(desc, "售价")
                                }
                                // 检查复合技能：*星和2星菜谱售价各+*%
                                val compositePattern = Regex("""(\d+)星和2星菜谱售价各\+(\d+)%""")
                                val match = compositePattern.find(desc)
                                if (match != null) {
                                    totalBonus += match.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查复合技能：2星和*星菜谱售价各+*%
                                val compositePattern2 = Regex("""2星和(\d+)星菜谱售价各\+(\d+)%""")
                                val match2 = compositePattern2.find(desc)
                                if (match2 != null) {
                                    totalBonus += match2.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查2火菜谱售价加成
                                val firePattern = Regex("""2火菜谱售价\+(\d+)%""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "3星菜谱售价+" -> {
                                if (desc.contains("3星菜谱售价+")) {
                                    totalBonus += extractNumberFromDesc(desc, "售价")
                                }
                                // 检查复合技能：*星和3星菜谱售价各+*%
                                val compositePattern = Regex("""(\d+)星和3星菜谱售价各\+(\d+)%""")
                                val match = compositePattern.find(desc)
                                if (match != null) {
                                    totalBonus += match.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查复合技能：3星和*星菜谱售价各+*%
                                val compositePattern2 = Regex("""3星和(\d+)星菜谱售价各\+(\d+)%""")
                                val match2 = compositePattern2.find(desc)
                                if (match2 != null) {
                                    totalBonus += match2.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查3火菜谱售价加成
                                val firePattern = Regex("""3火菜谱售价\+(\d+)%""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "4星菜谱售价+" -> {
                                if (desc.contains("4星菜谱售价+")) {
                                    totalBonus += extractNumberFromDesc(desc, "售价")
                                }
                                // 检查复合技能：*星和4星菜谱售价各+*%
                                val compositePattern = Regex("""(\d+)星和4星菜谱售价各\+(\d+)%""")
                                val match = compositePattern.find(desc)
                                if (match != null) {
                                    totalBonus += match.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查复合技能：4星和*星菜谱售价各+*%
                                val compositePattern2 = Regex("""4星和(\d+)星菜谱售价各\+(\d+)%""")
                                val match2 = compositePattern2.find(desc)
                                if (match2 != null) {
                                    totalBonus += match2.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查4火菜谱售价加成
                                val firePattern = Regex("""4火菜谱售价\+(\d+)%""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "5星菜谱售价+" -> {
                                if (desc.contains("5星菜谱售价+")) {
                                    totalBonus += extractNumberFromDesc(desc, "售价")
                                }
                                // 检查复合技能：*星和5星菜谱售价各+*%
                                val compositePattern = Regex("""(\d+)星和5星菜谱售价各\+(\d+)%""")
                                val match = compositePattern.find(desc)
                                if (match != null) {
                                    totalBonus += match.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查复合技能：5星和*星菜谱售价各+*%
                                val compositePattern2 = Regex("""5星和(\d+)星菜谱售价各\+(\d+)%""")
                                val match2 = compositePattern2.find(desc)
                                if (match2 != null) {
                                    totalBonus += match2.groupValues[2].toIntOrNull() ?: 0
                                }
                                // 检查5火菜谱售价加成
                                val firePattern = Regex("""5火菜谱售价\+(\d+)%""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "1星菜谱上限+" -> {
                                if (desc.contains("1星菜谱上限+")) {
                                    totalBonus += extractNumberFromDesc(desc, "上限")
                                }
                                // 检查1火菜谱上限加成
                                val firePattern = Regex("""1火菜谱上限\+(\d+)""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "2星菜谱上限+" -> {
                                if (desc.contains("2星菜谱上限+")) {
                                    totalBonus += extractNumberFromDesc(desc, "上限")
                                }
                                // 检查2火菜谱上限加成
                                val firePattern = Regex("""2火菜谱上限\+(\d+)""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "3星菜谱上限+" -> {
                                if (desc.contains("3星菜谱上限+")) {
                                    totalBonus += extractNumberFromDesc(desc, "上限")
                                }
                                // 检查3火菜谱上限加成
                                val firePattern = Regex("""3火菜谱上限\+(\d+)""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "4星菜谱上限+" -> {
                                if (desc.contains("4星菜谱上限+")) {
                                    totalBonus += extractNumberFromDesc(desc, "上限")
                                }
                                // 检查4火菜谱上限加成
                                val firePattern = Regex("""4火菜谱上限\+(\d+)""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                            "5星菜谱上限+" -> {
                                if (desc.contains("5星菜谱上限+")) {
                                    totalBonus += extractNumberFromDesc(desc, "上限")
                                }
                                // 检查5火菜谱上限加成
                                val firePattern = Regex("""5火菜谱上限\+(\d+)""")
                                val fireMatch = firePattern.find(desc)
                                if (fireMatch != null) {
                                    totalBonus += fireMatch.groupValues[1].toIntOrNull() ?: 0
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    return totalBonus
}

/**
 * 获取满足当前筛选条件的厨师列表
 */
private fun getChefsForBonusCalculation(
    allChefs: List<Chef>,
    skills: List<Skill>,
    showAll: Boolean,
    queryType: String,
    bonusType: String
): List<Chef> {
    val baseChefs = if (showAll) {
        allChefs
    } else {
        allChefs.filter { it.got }
    }

    return baseChefs.filter { chef ->
        val matchesQueryType = when (queryType) {
            "贵客厨师" -> isGuestChef(chef, skills)
            "基修厨师" -> isBasicCultivationChef(chef, skills)
            "光环厨师" -> isAuraChef(chef, skills)
            "采集厨师" -> isCollectionChef(chef, skills)
            else -> true
        }

        if (queryType == "基修厨师" && bonusType != "全部" && matchesQueryType) {
            matchesBonusType(chef, skills, bonusType)
        } else {
            matchesQueryType
        }
    }
}

/**
 * 厨师分类项目卡片 - 与选择厨师弹窗样式保持一致
 */
@Composable
fun ChefCategoryItemCard(
    chef: Chef,
    skills: List<Skill>,
    isGuestChefQuery: Boolean = false,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 2.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 1.dp)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp)
        ) {
            // 主要内容区域
            Column {
                // 第一行：厨师名字 + 星级
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = chef.name,
                        fontSize = 16.sp,
                        fontWeight = FontWeight.Medium
                    )

                    Spacer(modifier = Modifier.width(8.dp))

                    // 星级显示
                    Row {
                        repeat(chef.rarity) {
                            Icon(
                                imageVector = Icons.Default.Star,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary,
                                modifier = Modifier.size(12.dp)
                            )
                        }
                    }

                    // 采集点数显示（仅在采集厨师查询时显示）
                    if (!isGuestChefQuery) {
                        Spacer(modifier = Modifier.width(8.dp))
                        
                        val collectionPoints = getCollectionPointsText(chef)
                        if (collectionPoints.isNotEmpty()) {
                            Text(
                                text = collectionPoints,
                                fontSize = 11.sp,
                                color = MaterialTheme.colorScheme.secondary,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }
                }

                // 第二行：技能描述 - 根据查询类型选择不同的显示方式
                val skillDescription = if (isGuestChefQuery) {
                    getGuestRelatedSkillDescription(chef, skills)
                } else {
                    getChefSkillDescription(chef, skills)
                }
                
                Text(
                    text = skillDescription,
                    fontSize = 12.sp,
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.padding(top = 4.dp)
                )

                // 第三行：来源
                Text(
                    text = chef.origin.replace("<br>", "、"),
                    fontSize = 13.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 2.dp)
                )


            }
            
            // 右下角：拥有状态和修炼状态
            Column(
                modifier = Modifier.align(Alignment.BottomEnd),
                horizontalAlignment = Alignment.End
            ) {
                // 拥有状态
                Text(
                    text = if (chef.got) "已拥有" else "未拥有",
                    fontSize = 9.sp,
                    color = if (chef.got)
                        MaterialTheme.colorScheme.primary
                    else
                        Color.Red,
                    fontWeight = if (chef.got) FontWeight.Bold else FontWeight.Normal
                )

                // 只有已拥有的厨师才显示修炼状态
                if (chef.got) {
                    Text(
                        text = if (chef.ult) "已修炼" else "未修炼",
                        fontSize = 9.sp,
                        color = if (chef.ult)
                            MaterialTheme.colorScheme.primary
                        else
                            Color.Red,
                        fontWeight = if (chef.ult) FontWeight.Bold else FontWeight.Normal
                    )
                }
            }
        }
    }
}

/**
 * 检查厨师是否匹配指定的光环类型
 */
private fun matchesAuraType(chef: Chef, skills: List<Skill>, auraType: String): Boolean {
    if (!isAuraChef(chef, skills)) return false
    
    val skillDesc = getChefSkillDescription(chef, skills)
    
    return when (auraType) {
        "技法光环" -> {
            // 使用新的技法光环厨师判断逻辑
            isTechniqueAuraChef(chef, skills)
        }
        "售价光环" -> {
            // 使用新的售价光环厨师判断逻辑
            isPriceAuraChef(chef, skills)
        }
        else -> true
    }
}

/**
 * 检查售价光环厨师是否匹配指定的技法筛选类型
 * 售价光环厨师按effect字段判断相关技法类型
 */
private fun matchesAuraFilterTypeForPrice(chef: Chef, skills: List<Skill>, filterType: String): Boolean {
    if (filterType == "全部") return true
    if (!chef.hasUltimateSkill()) return false
    
    println("DEBUG: 检查厨师 ${chef.name} 的售价技法筛选，筛选类型: $filterType")
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 技法类型映射
    val typeMapping = mapOf(
        "炒" to "Stirfry",
        "煮" to "Boil", 
        "切" to "Knife",
        "炸" to "Fry",
        "烤" to "Bake",
        "蒸" to "Steam"
    )
    
    return when (filterType) {
                            "其他" -> {
            // 检查是否有不属于六种基础技法且不是被排除类型的effect
            val excludedTypes = listOf("OpenTime", "MaxEquipLimit", "Creation", "Meat", "Fish", "Vegetable", "GuestApearRate", "InvitationApearRate")
            ultimateSkills.any { skill ->
                skill.effect?.any { effect ->
                    val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
                    val isNotBasicTechnique = effect.type !in listOf("Bake", "Steam", "Boil", "Fry", "Knife", "Stirfry")
                    val isNotExcludedType = effect.type !in excludedTypes
                    conditionMatch && isNotBasicTechnique && isNotExcludedType
                } ?: false
            }
        }
        else -> {
            // 检查是否有匹配的技法类型
            val targetType = typeMapping[filterType]
            if (targetType != null) {
                ultimateSkills.any { skill ->
                    skill.effect?.any { effect ->
                        val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
                        val typeMatch = effect.type?.contains(targetType) == true
                        conditionMatch && typeMatch
                    } ?: false
                        }
                    } else {
                true
                }
            }
        }
}

/**
 * 判断是否为技法光环厨师
 * 按照查询采集编队页面的实验室中查询光环厨师逻辑
 */
private fun isTechniqueAuraChef(chef: Chef, skills: List<Skill>): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    // 获取厨师的所有修炼技能
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    // 检查是否有符合条件的技法光环技能
    return ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            // 条件1：condition必须是"Partial"或"Next"
            val conditionMatch = effect.condition == "Partial" || effect.condition == "Next"
            
            // 条件2：type必须是技法类型
            val typeMatch = effect.type in listOf("Bake", "Steam", "Boil", "Fry", "Knife", "Stirfry")
            
            // 条件3：value必须大于0
            val valueMatch = (effect.value ?: 0) > 0
            
            conditionMatch && typeMatch && valueMatch
        } ?: false
    }
}

/**
 * 判断是否为售价光环厨师
 * 售价光环厨师：其他光环厨师（不是技法光环的光环厨师），但要排除type为OpenTime、MaxEquipLimit、Creation、Meat、Fish、Vegetable、GuestApearRate、InvitationApearRate的厨师
 */
private fun isPriceAuraChef(chef: Chef, skills: List<Skill>): Boolean {
    // 首先必须是光环厨师
    if (!isAuraChef(chef, skills)) return false
    
    // 如果是技法光环厨师，则不是售价光环厨师
    if (isTechniqueAuraChef(chef, skills)) return false
    
    // 排除特定类型的厨师
    val ultimateSkills = chef.getAllUltimateSkills().mapNotNull { skillId ->
        skills.find { it.skillId == skillId }
    }
    
    val excludedTypes = listOf("OpenTime", "MaxEquipLimit", "Creation", "Meat", "Fish", "Vegetable", "GuestApearRate", "InvitationApearRate")
    
    val hasExcludedEffect = ultimateSkills.any { skill ->
        skill.effect?.any { effect ->
            (effect.condition == "Partial" || effect.condition == "Next") && 
            effect.type in excludedTypes
        } ?: false
    }
    
    // 如果有被排除类型的effect，则不是售价光环厨师
    if (hasExcludedEffect) return false
    
    // 如果是光环厨师但不是技法光环厨师且不是被排除类型的厨师，则是售价光环厨师
    return true
}

/**
 * 获取厨师的effect字段信息
 * 用于在UI中显示effect字段的详细信息
 */
private fun getEffectFieldInfo(chef: Chef, skills: List<Skill>): String {
    if (!chef.hasUltimateSkill()) return ""
    
    val skillsList = chef.getAllUltimateSkills()
    val effectInfos = mutableListOf<String>()
    
    for (ultimateSkillId in skillsList) {
        val skill = skills.find { it.skillId == ultimateSkillId }
        if (skill != null && skill.effect.isNotEmpty()) {
            for (effect in skill.effect) {
                val effectInfo = buildString {
                    if (effect.condition.isNotEmpty()) {
                        append("condition: ${effect.condition}")
                    }
                    if (effect.type.isNotEmpty()) {
                        if (isNotEmpty()) append(", ")
                        append("type: ${effect.type}")
                    }
                    if (effect.conditionType.isNotEmpty()) {
                        if (isNotEmpty()) append(", ")
                        append("conditionType: ${effect.conditionType}")
                    }
                    if (effect.value > 0) {
                        if (isNotEmpty()) append(", ")
                        append("value: ${effect.value}")
                    }
                }
                if (effectInfo.isNotEmpty()) {
                    effectInfos.add(effectInfo)
                }
            }
        }
    }
    
    return if (effectInfos.isNotEmpty()) {
        "Effect: ${effectInfos.joinToString(" | ")}"
    } else {
        ""
    }
}

/**
 * 计算采集厨师的评分
 * 公式：素材加成 + 暴击率 × 暴击素材
 */
private fun calculateCollectionScore(chef: Chef, skills: List<Skill>): CollectionScore {
    var materialBonus = 0      // 素材加成
    var critChance = 0         // 暴击率
    var critMaterial = 0       // 暴击素材
    
    // 检查厨师自身技能
    if (chef.skill != 0) {
        val skill = skills.find { it.skillId == chef.skill }
        if (skill != null) {
            val bonus = parseCollectionSkillBonus(skill.desc)
            materialBonus += bonus.materialBonus
            critChance += bonus.critChance
            critMaterial += bonus.critMaterial
        }
    }
    
    // 检查厨师修炼技能
    chef.getAllUltimateSkills().forEach { sid ->
        val skill = skills.find { it.skillId == sid }
        if (skill != null) {
            val bonus = parseCollectionSkillBonus(skill.desc)
            materialBonus += bonus.materialBonus
            critChance += bonus.critChance
            critMaterial += bonus.critMaterial
        }
    }
    
    val totalScore = materialBonus + (critChance * critMaterial / 100)  // 暴击率是百分比，需要除以100
    val critProduct = critChance * critMaterial / 100  // 暴击率×暴击素材
    
    return CollectionScore(
        totalScore = totalScore,
        materialBonus = materialBonus,
        critChance = critChance,
        critMaterial = critMaterial,
        critProduct = critProduct
    )
}

/**
 * 解析采集技能加成
 */
private fun parseCollectionSkillBonus(skillDesc: String): CollectionSkillBonus {
    var materialBonus = 0      // 素材加成
    var critChance = 0         // 暴击率
    var critMaterial = 0       // 暴击素材
    
    // 1. 暴击技能：技能描述包含"概率额外获得素材"相关文字
    val critPatterns = arrayOf(
        Regex("探索时有(\\d+)%概率额外获得(\\d+)%的?素材"),  // 忌璃格式：探索时有30%概率额外获得80%的素材
        Regex("有(\\d+)%概率额外获得(\\d+)%素材"),        // 四郎格式：有30%概率额外获得60%素材
        Regex("(\\d+)%概率额外获得(\\d+)%素材")           // 简化格式：30%概率额外获得60%素材
    )
    
    for (pattern in critPatterns) {
        val critMatch = pattern.find(skillDesc)
        if (critMatch != null) {
            critChance = critMatch.groupValues[1].toInt()
            critMaterial = critMatch.groupValues[2].toInt()
            break
        }
    }
    
    // 2. 素材加成：技能描述包含"素材获得+X%"（不包括"全体*类素材获得+X%"）
    val materialGainPattern = Regex("素材获得\\+(\\d+)%")
    val materialGainMatch = materialGainPattern.find(skillDesc)
    if (materialGainMatch != null) {
        // 排除"全体*类素材获得+X%"的情况
        if (!skillDesc.contains("全体") || !skillDesc.contains("类素材获得")) {
            materialBonus = materialGainMatch.groupValues[1].toInt()
        }
    }
    
    return CollectionSkillBonus(materialBonus, critChance, critMaterial)
}

/**
 * 采集厨师评分数据类
 */
data class CollectionScore(
    val totalScore: Int,       // 总分：素材加成 + 暴击率 × 暴击素材
    val materialBonus: Int,    // 素材加成
    val critChance: Int,       // 暴击率
    val critMaterial: Int,     // 暴击素材
    val critProduct: Int       // 暴击率 × 暴击素材
)

/**
 * 采集技能加成数据类
 */
data class CollectionSkillBonus(
    val materialBonus: Int,    // 素材加成
    val critChance: Int,       // 暴击率
    val critMaterial: Int      // 暴击素材
)

/**
 * 检查厨师是否匹配指定的采集类型（多选版本）
 * 要求厨师必须同时拥有所有选中的采集类型
 */
private fun matchesCollectionTypes(chef: Chef, collectionTypes: Set<String>): Boolean {
    if (collectionTypes.isEmpty()) return true
    
    return collectionTypes.all { type ->
        when (type) {
            "肉" -> chef.meat > 0
            "菜" -> chef.veg > 0
            "鱼" -> chef.fish > 0
            "面" -> chef.creation > 0
            else -> false
        }
    }
}

/**
 * 检查厨师是否匹配指定的采集类型（单选版本，保留兼容性）
 */
private fun matchesCollectionType(chef: Chef, collectionType: String): Boolean {
    if (collectionType == "全部") return true
    
    return when (collectionType) {
        "肉" -> chef.meat > 0
        "菜" -> chef.veg > 0
        "鱼" -> chef.fish > 0
        "面" -> chef.creation > 0
        else -> true
    }
}

/**
 * 获取厨师的采集点数文本
 */
private fun getCollectionPointsText(chef: Chef): String {
    val points = mutableListOf<String>()
    
    // 添加各种采集点数
    if (chef.meat > 0) points.add("肉${chef.meat}")
    if (chef.fish > 0) points.add("鱼${chef.fish}")
    if (chef.veg > 0) points.add("菜${chef.veg}")
    if (chef.creation > 0) points.add("面${chef.creation}")
    
    return if (points.isNotEmpty()) {
        "(${points.joinToString(" ")})"
    } else {
        ""
    }
}